package com.ambow.poi;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExportExecServlet extends HttpServlet {

	private static final long serialVersionUID = -2912332646148125437L;

	@Override
	protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		// 声明一个工作薄
		Workbook workbook = new XSSFWorkbook();  
		// 生成一个表格
		Sheet sheet = workbook.createSheet("测试sheet");

		// 产生表格标题行
		Row row = sheet.createRow(0);
		for (int i = 0; i < 5; i++) {
			Cell cell = row.createCell(i);
			cell.setCellValue("标题列第" + i+"列数据");
		}

		for (int i = 1; i < 1000; i++) {
			row = sheet.createRow(i);
			for (int j = 0; j < 5; j++) {
				Cell cell = row.createCell(j);
				cell.setCellValue("测试数据" + i + "行" + j + "列");
			}
		}
		OutputStream out = arg1.getOutputStream();
		String fileName = "导出数据"+ new SimpleDateFormat("yyyy-MM-dd").format(new Date())+ ".xlsx"; // 生成文件名字
		// 设置响应头和下载保存的文件名
		arg1.setHeader("content-disposition","attachment;filename="+ new String(fileName.getBytes("gb2312"),"iso8859-1"));
		// 定义输出类型
		arg1.setContentType("application/vnd.ms-excel");
		arg1.setContentType("application/download");
		try {
			workbook.write(out);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("export --------------------------");
		out.close();
	}

}
